package com.chunxuan.langquan.ui.activity.live;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.support.util.Logg;
import com.m7.imkfsdk.utils.ToastUtils;
import com.tencent.rtmp.ITXLivePlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

import java.nio.charset.StandardCharsets;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import static com.tencent.rtmp.TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
import static com.tencent.rtmp.TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;

public class PlayBackRoomActivity extends AppCompatActivity implements View.OnClickListener {
    private TXVodPlayer mVodPlayer ;               //直播拉流的视频播放器
    private TXCloudVideoView mVideoView;
    private ImageView mImageLoading;          //显示视频缓冲动画
    private boolean mIsPlaying = false;
    private PopupWindow popupWindow;
    private TextView tvSpeed;
    public static void actionStart(Context context,String pullUrl) {
        Intent intent = new Intent(context, PlayBackRoomActivity.class);
        intent.putExtra("url",pullUrl);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_live_room);
        hideBottomUIMenu();//隐藏虚拟按键，否则全屏时虚拟按键会影响视频播放进度条的调整。
        initialize();

    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy();
    }

    private void initialize() {
        initPlayView();
        initPlayButton();
        initNavigationBack();
        // 初始化完成之后自动播放
        startPlay();
    }

    private void initPlayView() {
        mVideoView = (TXCloudVideoView) findViewById(R.id.video_view);
        mVodPlayer = new TXVodPlayer(this);
//        mVodPlayer.setRenderMode(RENDER_MODE_ADJUST_RESOLUTION);
        mVodPlayer.setRenderMode(RENDER_MODE_FULL_FILL_SCREEN);
//        mVodPlayer.setRenderMode(RENDER_MODE_FULL_FILL_SCREEN);
        mImageLoading = (ImageView) findViewById(R.id.liveplayer_iv_loading);
//        pb=findViewById(R.id.player_pb);
        tvSpeed=findViewById(R.id.tv_speed_settings);
        tvSpeed.setOnClickListener(this);
    }

    private void initPlayButton() {

    }

    private void togglePlay() {
        if (mIsPlaying) {
            stopPlay();
        } else {
            startPlay();
        }
    }

    private void initNavigationBack() {
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destroy();
                finish();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            destroy();
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public void startPlay() {
//        startLoadingAnimation();
        mVodPlayer.setPlayerView(mVideoView);
//        mVodPlayer.seek(seekb);
        mVodPlayer.startPlay(getIntent().getStringExtra("url"));

    }

    @Override
    public void onBackPressed() {
        stopPlay();
        super.onBackPressed();
    }

    private void stopPlay() {
        if (!mIsPlaying) {
            return;
        }
        if (mVodPlayer != null) {

            mVodPlayer.stopPlay(true);
        }
        mIsPlaying = false;

        //处理UI相关操作
        onPlayStop();
    }

    public void onPlayStop() {
        stopLoadingAnimation();
    }

    public void onPlayStart(int code) {
        Log.e("设置背景", "onPlayStart");
        switch (code) {
            case Constants.PLAY_STATUS_SUCCESS:
                startLoadingAnimation();
                break;
            case Constants.PLAY_STATUS_INVALID_SECRET_RTMP_URL:
                new AlertDialog.Builder(this)
                        .setTitle("播放出错")
                        .setMessage("请检查地址")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse(Constants.LIVE_PLAYER_REAL_TIME_PLAY_DOCUMENT_URL);
                        startActivity(new Intent(Intent.ACTION_VIEW, uri));
                        dialog.dismiss();
                    }
                }).show();
                break;
            default:
                break;
        }
        if (code != Constants.PLAY_STATUS_SUCCESS) {

            ToastUtils.showShort(this, "播放失败");
        } else {
            Log.e("设置背景", "====");

        }

    }

    private void startLoadingAnimation() {
        if (mImageLoading != null) {
            mImageLoading.setVisibility(View.VISIBLE);
            ((AnimationDrawable) mImageLoading.getDrawable()).start();
        }
    }

    private void stopLoadingAnimation() {
        if (mImageLoading != null) {
            mImageLoading.setVisibility(View.GONE);
            ((AnimationDrawable) mImageLoading.getDrawable()).stop();
        }
    }

    private void destroy() {
        if (mVodPlayer != null) {
            mVodPlayer.stopPlay(true);
            mVodPlayer = null;
        }
        if (mVideoView != null) {
            mVideoView.onDestroy();
            mVideoView = null;
        }
    }

    @Override
    public void onClick(View v) {
        if(null==mVodPlayer){
            return;
        }
        switch (v.getId()){
            case R.id.tv_speed_settings:
                setSpeed();
                break;
        }
    }
    //菜单按钮的单机事件
    public void setSpeed(){
        TextView tv08,tv10,tv125,tv15,tv20;
        //获取自定义菜单的布局文件
        View popupWindow_view=getLayoutInflater().inflate(R.layout.speed_menu,null,false);
        //创建popupWindow实例，设置菜单的宽度和高度
        popupWindow=new PopupWindow(popupWindow_view, ActionBar.LayoutParams.WRAP_CONTENT,ActionBar.LayoutParams.WRAP_CONTENT,true);
        //设置菜单显示在按钮的下面
//        popupWindow.showAsDropDown(findViewById(R.id.tv_speed_settings),0,0);
        //设置菜单显示在按钮的上面
        int[] loc=new int[2];
        tvSpeed.getLocationOnScreen(loc);
        popupWindow.showAtLocation(tvSpeed, Gravity.NO_GRAVITY,(loc[0]+tvSpeed.getWidth()/2)-tvSpeed.getWidth()/2,loc[1]-tvSpeed.getHeight()-70);
        tv08=popupWindow_view.findViewById(R.id.tv_08);
        tv10=popupWindow_view.findViewById(R.id.tv_10);
        tv125=popupWindow_view.findViewById(R.id.tv_125);
        tv15=popupWindow_view.findViewById(R.id.tv_15);
        tv20=popupWindow_view.findViewById(R.id.tv_20);
        tv08.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVodPlayer.setRate((float) 0.8);
                popupWindow.dismiss();
            }
        });
        tv10.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVodPlayer.setRate((float) 1.0);
                popupWindow.dismiss();
            }
        });
        tv125.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVodPlayer.setRate((float) 1.25);
                popupWindow.dismiss();
            }
        });
        tv15.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVodPlayer.setRate((float) 1.5);
                popupWindow.dismiss();
            }
        });
        tv20.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVodPlayer.setRate((float) 2.0);
                popupWindow.dismiss();
            }
        });

        //单机其它位置隐藏菜单
        popupWindow_view.setOnTouchListener(new View.OnTouchListener(){

            @Override
            public boolean onTouch(View v, MotionEvent event){

                //如果菜单存在并且处于显示状态
                if (popupWindow!=null&&popupWindow.isShowing()){

                    popupWindow.dismiss();//关闭菜单
                    popupWindow=null;
                }
                return false;
            }
        });


    }
}